﻿using DocumentFormat.OpenXml.Lite.Core;
using DocumentFormat.OpenXml.Lite.Core.ContentType;
using DocumentFormat.OpenXml.Lite.Core.DocumentFS;
using DocumentFormat.OpenXml.Lite.Core.Interfaces;
using DocumentFormat.OpenXml.Lite.Core.Office;
using DocumentFormat.OpenXml.Lite.Core.Relationship;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.Base;
using DocumentFormat.OpenXml.Lite.WordprocessingML;
using DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML
{
    public static class Spreadsheet
    {
        public static string AddWorkbookFor(this Document doc, ISerializable obj, Workbook wb, string filename)
        {
            Embedding workbook;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                wb.Save(ms);
                workbook = new Embedding(ms.ToArray(), filename);
            }

            Default def = new Default()
            {
                Extension = "xlsx",
                ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            };

            return DocumentManager.Instance.FindDocument(doc.Id)
                .AddEmbeddingFor(obj, workbook, RelationshipURI.Package, def);
        }

        public static Workbook GetEmbeddedWorkbookFor(this Document doc, ISerializable obj, string relId)
        {
            Embedding em = DocumentManager.Instance
                .FindDocument(doc.Id).FindElementFor<Embedding>(obj, relId);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(em.Data))
            {
                return DocumentManager.Instance.OpenExcelDocument(ms);
            }
        }
    }
}
